import {
  fixPageApi,
  addFixApi,
  editFixApi,
  delFixApi
} from '@/api/workflow/fix'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { FixModel } from '@/api/model/fix-model'
import { userInfo } from '~/types/user'
import { userInfoModel } from '@/api/model/userModel'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | 'check'>
  handleTag: Ref<string>
  fixModalShow: Ref<boolean>
  fixForm: Ref<Partial<FixModel>>
  proTableInst: Ref<ProTableInst | null>
  userInfo: Ref<userInfo<userInfoModel>>
}

export const useFixApi = ({
  handleType,
  handleTag,
  fixModalShow,
  fixForm,
  proTableInst,
  userInfo
}: Props) => {
  const confirmLoading = ref(false)

  // 获取维修列表
  const fetchFixPage = async (
    pageRequest: PageRequest,
    queryParams: FixModel
  ) => {
    const res = await fixPageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改维修
  const fetchAddOrEditFix = async (msg?: string) => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addFixApi : editFixApi
    const data =
      handleType.value === 'add'
        ? {
            ...fixForm.value,
            receivePerson: userInfo.value.userName,
            receivePersonId: userInfo.value.userId,
            receiveBranch: userInfo.value.orgName,
            receiveBranchId: userInfo.value.orgId,
            receiveDate: dayjs().format('YYYY-MM-DD')
          }
        : {
            ...fixForm.value
          }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await fetch(data)
    console.log('data', data, userInfo.value.userName, userInfo.value)
    if (res.code === '0000') {
      useMsg('success', msg || handleTag.value + '成功')
      proTableInst.value?.reload()
      fixModalShow.value = false
    }

    confirmLoading.value = false
  }

  // 删除维修
  const fetchDelFix = async (id) => {
    const res = await delFixApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  return {
    fetchFixPage,
    fetchAddOrEditFix,
    fetchDelFix,
    confirmLoading
  }
}
